package cn.com.pansky.action.unit;

import java.io.File;
import java.sql.Timestamp;
import java.util.UUID;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;
import cn.com.pansky.action.imgContrast.ImgContrast;
import cn.com.pansky.action.logs.Log;
import cn.com.pansky.sdk.API;
import cn.com.pansky.service.CommonService;
import cn.com.pansky.service.UserService;
import cn.com.pansky.util.CardNumUtil;
import cn.com.pansky.util.DateUtil;
import cn.com.pansky.util.EncryptionUtils;
import cn.com.pansky.util.ImageBinaryUtil;
import cn.com.pansky.util.LssConstant;
import cn.com.pansky.util.MD5Util;

import com.alibaba.fastjson.JSONObject;

public class UnitUserAction extends CommonAction{
	private Log log = new Log();
	
	UserService us = new UserService();
	CommonService cs = new CommonService();
	
	
	
	/**
	 * 升级版单位注册
	 * @throws Exception
	 */
	public void registerV2() throws Exception {
		
		//日志记录start
		String AF001 = log.start("ZC_");
		
		JSONObject data = new JSONObject();
		String AA032 =  getParam("AA032");
		if(!AA032.equals(context.getSessionVal("AA032"))) {
			data.put("isPass", false);
			data.put("info", "手机号与接收短信手机号不一致！");
			context.getDatas().put("result", data);
			return ;
		}
		
		if (context.getSessionVal("AA032")!=null && context.getSessionVal("AF016")!=null) {
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF014 desc) where rownum = 1", 
					context.getSessionVal("AA032"),getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					data.put("isPass", false);
					data.put("info", "验证码超时");
					context.getDatas().put("result", data);
					return ;
				}else{
					context.getServletSession().removeAttribute("AF016");
				}
			} else {
				data.put("isPass", false);
				data.put("info", "验证码输入错误");
				context.getDatas().put("result", data);
				return ;
			}
		}else{
			data.put("isPass", false);
			data.put("info", "验证码已失效，请重新获取");
			context.getDatas().put("result", data);
			return ;
		}
		
		String AAB301 = getParam("AAB301");
		String AAF013 = context.getParam("AAF013");
		String AAZ070 = context.getParam("AAZ070");
		String AA036 = "";
		if(null != context.getParam("AA036")){
			AA036 = context.getParam("AA036");
		} else {
			AA036 = AA032;
		}
		
		String userId = UUID.randomUUID().toString();
		
//		获取身份证照片
		String BIC106 = getParam("BIC106"); // 身份证图片
		File file1 = new File(BIC106);// 身份证上传后的临时文件
		JSONObject json = null;
		double num = 0.0;
		if (!file1.exists()) {
			data.put("isPass", false);
			data.put("info", "身份证照片不可为空！");
			context.getDatas().put("result", data);
			return ;
		} else {
			json = cs.idendetify(file1.getPath());
		}
		
//		获取CA001
		String queryRC03 = urlConfig.getVar("queryRC03");
		Model model = SqlHelper.queryOne(queryRC03, json.get("CA006"));
		String CA001 = "";
		if (null == model) {
			CA001 = UUID.randomUUID().toString();
		} else {
			CA001 = model.getString("CA001");
		}		
		
//		获取刷脸照片
		String image_best = context.getParam("image_best");
		String image_env = context.getParam("image_env");
		String delta = context.getParam("delta");
		File file2 = new File(image_best);// 身份证上传后的临时文件
		if (!file2.exists()) {
			data.put("isPass", false);
			data.put("info", "人脸照片不可为空！");
			context.getDatas().put("result", data);
			return ;
		} else {
			JSONObject result = ImgContrast.imgCompare(BIC106, image_best, image_env, delta);
			if(0 != result.getIntValue("code")){
				data.put("isPass", false);
				data.put("info", "请确认身份证与刷脸是同一人！");
				context.getDatas().put("result", data);
				return ;
			}else{
				num = result.getDoubleValue("confidence");
				if (num < LssConstant.CONFIDENCE) {
					file1.delete();
					file2.delete();
					data.put("isPass", false);
					data.put("info", "与证件照片相似度过低！");
					context.getDatas().put("result", data);
					return ;
				}
			}
		}
		
		// 保存用户信息到远程接口
		JSONObject object = sendToBusiness(userId, json, AA036, BIC106, image_best, AAF013, AAB301, AAZ070);
		
		if (object.getBooleanValue("SUCCESS")) {
//			2.保存用户
			addUser(userId,CA001,json,AA032,AA036);
				
//			3.保存密码
			addPass(userId);
			data.put("id", userId);
			data.put("isPass", true);
			context.getDatas().put("result", data);
			
//			将身份证照片存库
			String s1 = urlConfig.getVar("queryRC05Byca001");
			Model m2 = SqlHelper.queryOne(s1, CA001);
			String id = "";
			if (m2 != null) {
				id = m2.getString("CA020");
			} 
			
			cs.isnertRC05(CA001, BIC106, id);
			
//			将刷脸图片存库
			String findFeatures = urlConfig.getVar("findFeatures");
			Model m = SqlHelper.queryOne(findFeatures, CA001);
			String id2 = "";
			if (m != null) {
				id2 = m.getString("CA011");
			}
			cs.isnertRC06(image_best, CA001, num, id2);
			file1.delete();
			file2.delete();
			
		} else {
			System.out.println(object);
			file1.delete();
			file2.delete();
			data.put("isPass", false);
			data.put("info", "业务系统正在维护,请稍后再试！");
			context.getDatas().put("result", data);
		}
		
		//日志记录end
		boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"), CA001, userId);
		System.out.println("日志：机构版新用户注册："+result);
		
		handleResult(object);
	}

	
	public void register() throws Exception {
		JSONObject data = new JSONObject();
		String AA032 =  getParam("AA032");
		if(!AA032.equals(context.getSessionVal("AA032"))) {
			data.put("isPass", false);
			data.put("info", "手机号与接收短信手机号不一致！");
			context.getDatas().put("result", data);
			return ;
		}
		
		if (context.getSessionVal("AA032")!=null && context.getSessionVal("AF016")!=null) {
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF014 desc) where rownum = 1", 
					context.getSessionVal("AA032"),getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					data.put("isPass", false);
					data.put("info", "验证码超时");
					context.getDatas().put("result", data);
					return ;
				}else{
					context.getServletSession().removeAttribute("AF016");
				}
			} else {
				data.put("isPass", false);
				data.put("info", "验证码输入错误");
				context.getDatas().put("result", data);
				return ;
			}
		}else{
			data.put("isPass", false);
			data.put("info", "验证码已失效，请重新获取");
			context.getDatas().put("result", data);
			return ;
		}
		
		String AAB301 = getParam("AAB301");
		String AAF013 = context.getParam("AAF013");
		String AAZ070 = context.getParam("AAZ070");
		String AA036 = "";
		if(null != context.getParam("AA036")){
			AA036 = context.getParam("AA036");
		} else {
			AA036 = AA032;
		}
		
		String userId = UUID.randomUUID().toString();
		
//		获取身份证照片
		String BIC106 = getParam("BIC106"); // 身份证图片
		File file1 = new File(BIC106);// 身份证上传后的临时文件
		JSONObject json = null;
		double num = 0.0;
		if (!file1.exists()) {
			data.put("isPass", false);
			data.put("info", "身份证照片不可为空！");
			context.getDatas().put("result", data);
			return ;
		} else {
			json = cs.idendetify(file1.getPath());
		}
		
//		获取CA001
		String queryRC03 = urlConfig.getVar("queryRC03");
		Model model = SqlHelper.queryOne(queryRC03, json.get("CA003"), json.get("CA006"));
		String CA001 = "";
		if (null == model) {
			CA001 = UUID.randomUUID().toString();
		} else {
			CA001 = model.getString("CA001");
		}		
		
//		获取刷脸照片
		String BIC107 = context.getParam("BIC107");
		File file2 = new File(BIC107);// 身份证上传后的临时文件
		if (!file2.exists()) {
			data.put("isPass", false);
			data.put("info", "人脸照片不可为空！");
			context.getDatas().put("result", data);
			return ;
		} else {
			num = ImgContrast.imgContrast(BIC106, BIC107);
			if (num < LssConstant.CONFIDENCE) {
				file1.delete();
				file2.delete();
				data.put("isPass", false);
				data.put("info", "与证件照片相似度过低！");
				context.getDatas().put("result", data);
				return ;
			}
		}
		
		// 保存用户信息到远程接口
		JSONObject object = sendToBusiness(userId, json, AA036, BIC106, BIC107, AAF013, AAB301, AAZ070);
		
		if (object.getBooleanValue("SUCCESS")) {
//			2.保存用户
			addUser(userId,CA001,json,AA032,AA036);
				
//			3.保存密码
			addPass(userId);
			data.put("id", userId);
			data.put("isPass", true);
			context.getDatas().put("result", data);
			
//			将身份证照片存库
			String s1 = urlConfig.getVar("queryRC05Byca001");
			Model m2 = SqlHelper.queryOne(s1, CA001);
			String id = "";
			if (m2 != null) {
				id = m2.getString("CA020");
			} 
			
			cs.isnertRC05(CA001, BIC106, id);
			
//			将刷脸图片存库
			String findFeatures = urlConfig.getVar("findFeatures");
			Model m = SqlHelper.queryOne(findFeatures, CA001);
			String id2 = "";
			if (m != null) {
				id2 = m.getString("CA011");
			}
			cs.isnertRC06(BIC107, CA001, num, id2);
			file1.delete();
			file2.delete();
			
		} else {
			System.out.println(object);
			file1.delete();
			file2.delete();
			data.put("isPass", false);
			data.put("info", "业务系统正在维护,请稍后再试！");
			context.getDatas().put("result", data);
		}
		
		handleResult(object);
	}
	
	/**
	 * 保存到业务库
	 * @param userId
	 * @param json
	 * @param AA036
	 * @param BIC104
	 * @param BIC107
	 * @param AAF013
	 * @param AAB301
	 * @param AAZ070
	 * @return
	 */
	private JSONObject sendToBusiness(String userId, JSONObject json, String AA036, String BIC104, 
			String BIC107, String AAF013, String AAB301, String AAZ070) {
		JSONObject param = new JSONObject();
		param.put("AAA121", "RGUSER"); //业务类型
		param.put("AAB301", AAB301); // 机构代码
		param.put("AAF013", AAF013); // 所属乡镇
		param.put("AAZ070", AAZ070); // 所属村
		param.put("AAC002", json.get("CA006")); // 身份证号码
		param.put("AAC003", json.get("CA003")); // 姓名
		param.put("AAC004", cs.getAac004(json.getString("CA050"))); // 性别
		param.put("AAC045", AA036); // 联系电话
		param.put("AAE011", userId); // 用户ID
		BIC104 = ImageBinaryUtil.getImageBinary(BIC104);
		BIC107 = ImageBinaryUtil.getImageBinary(BIC107);
		param.put("BIC104", BIC104);
		param.put("BIC107", BIC107);
		JSONObject object = API.sendController("rgUserController.json", param);
		return object;
	}

	
	/**
	 * 保存密码信息
	 * @param userId
	 */
	private void addPass(String userId) {
		String pass = EncryptionUtils.md5(getParam("AA002"));
		String savePass = urlConfig.getVar("savePass"); // 获取sql
		SqlHelper.execute(savePass, userId, pass);
	}

	
	/**
	 * 保存用户信息到本地
	 * @param userId
	 * @param CA001
	 * @param json
	 * @param AA032
	 * @param AA036
	 */
	private void addUser(String userId, String CA001, JSONObject json, String AA032, String AA036) {
		
		//自然人添加数据：
		String queryRC03 = urlConfig.getVar("queryRC03");
		String addRC03 = urlConfig.getVar("addRC03");
		
		Model model = SqlHelper.queryOne(queryRC03, json.get("CA006"));
		if (null == model) {
			SqlHelper.execute(addRC03, CA001, json.get("CA003"), json.get("CA006"), json.get("CA009"), cs.getValueByName("AAC005", json.getString("CA051")), cs.getAac004(json.getString("CA050")), json.get("CA052"));
			String addRC10 = urlConfig.getVar("addRC10");
			SqlHelper.execute(addRC10, userId, CA001, "1", AA032, DateUtil.current19Time(), AA036);
		} else {
			String addRC10 = urlConfig.getVar("addRC10");
			SqlHelper.execute(addRC10, userId, model.get("CA001"), "1", AA032, DateUtil.current19Time(), AA036);
		}
	}
	
	/**
	 * 发送短信验证码
	 */
	public void sendCode() {
		String AA032 = getParam("AA032");
		String type = getParam("TYPE");
		if("login".equals(type)) {
			//登录处理
			us.sendLoginCode(AA032, "1"); //单位用户
		}else if("reg".equals(type)) {
			//注册用户
			register(AA032);
		}
	}
	
	/**
	 * 注册用户
	 * @param AA032
	 */
	private void register(String AA032) {
		JSONObject data = new JSONObject();
		//注册
		if(CardNumUtil.phoneNumber(AA032)){
			String sql = urlConfig.getVar("userIsExists");
			// 根据身份证获取用户信息
			Model m = SqlHelper.queryOne(sql, AA032);
			if(m != null) {
				String AAE016 = m.getString("AAE016");
				switch (Integer.parseInt(AAE016)) {
				case 0:
					data.put("isPass", false);
					data.put("info", "存在已登记账户，状态为未审核！");
					data.put("state", 0);
					break;
				case 1:
					data.put("isPass", false);
					data.put("info", "存在已登记账户，请直接登录！");
					data.put("state", 1);
					break;

				default:
					try {
						JSONObject obj = cs.aliyunSms(AA032);
						if (!"0".equals(obj.getString("code"))) {
							JSONObject json = new JSONObject();
							json.put("isPass", false);
							json.put("info", obj.getString("msg"));
							context.getDatas().put("result", json);
							return;
						} else {
							context.getServletSession().setAttribute("AA032", AA032);
							context.getServletSession().setAttribute("AF016", obj.getString("content"));
							JSONObject json = new JSONObject();
							json.put("isPass", true);
							context.getDatas().put("result", json);
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			}else{
				try {
					JSONObject obj = cs.aliyunSms(AA032);
					if (!"0".equals(obj.getString("code"))) {
						JSONObject json = new JSONObject();
						json.put("isPass", false);
						json.put("info", obj.getString("msg"));
						context.getDatas().put("result", json);
						return;
					} else {
						context.getServletSession().setAttribute("AA032", AA032);
						context.getServletSession().setAttribute("AF016", obj.getString("content"));
						JSONObject json = new JSONObject();
						json.put("isPass", true);
						context.getDatas().put("result", json);
						return;
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		} else {
			data.put("isPass", false);
			data.put("info", "请输入正确的手机号");
		}
		context.getDatas().put("result", data);
	}

	/**
	 * 发送短信验证码
	 * @param AA032
	 * @param data
	 * @throws Exception 
	 */
//	private void send(String AA032, JSONObject data) throws Exception {
//		JSONObject obj = cs.aliyunSms(AA032);
//		String code = obj.getString("content");
//		context.getServletSession().setAttribute("AA032", AA032);
//		context.getServletSession().setAttribute("AF016", code);
//		JSONObject json = new JSONObject();
//		json.put("isPass", true);
//		json.put("info", "验证码发送成功");
//		context.getDatas().put("result", json);
//		SqlHelper.execute("insert into CA20 values(${~UUID}, ?, ?, ?, ?)", AA032,
//				new java.sql.Timestamp(System.currentTimeMillis()),code,new Timestamp(System.currentTimeMillis()).getTime());
//		
//		data.put("isPass", true);
//		data.put("info", "短信验证码发送成功");
//		context.getDatas().put("result", data);
//	}

	/**
	 * 登录
	 */
	public void login() {
		String AA032 = getParam("AA032");
		String password = getParam("AA002");
		String sql = "SELECT A.AA001, B.AA002, A.AA032, A.AA003 from RC10 A , RA02 B WHERE A.AA001 = B.AA001 AND A.AA003='1' AND A.AA005='0' AND A.AAE016='1' AND A.AA032 = ?";
		Model m = SqlHelper.queryOne(sql, AA032);
		JSONObject data = new JSONObject();
		if(m != null) {
			String aa002 = m.getString("AA002");
			if(MD5Util.string2MD5(password).equals(aa002)) {
				context.getServletSession().setAttribute("user", m);//session中保存用户信息
//				用户id + 20161008 + MD5(用户ID + 用户密码 + 20161008)
//				20161008 是用户登录日期
				String token = m.getString("AA001")+"_"+DateUtil.current8_Time()+"_"+EncryptionUtils.md5(m.getString("AA001")+m.getString("AA002")+DateUtil.current8_Time());
				data.put("AA032", getParam("AA032"));
				data.put("AA001", m.getString("AA001"));
				data.put("token", token);
				data.put("isPass", true);
			}else{
				data.put("isPass", false);
				data.put("info", "密码错误！");
			}
		}else{
			data.put("isPass", false);
			data.put("info", "用户不存在或者未审核通过！");
		}
		context.getDatas().put("result", data);
	}
	
	
	/**
	 * 动态验证码登录
	 */
	public void codeLogin() {
		
		String AA032 = (String) context.getSessionVal("AA032");
		if(null == AA032) {
			datas.put("isPass", false);
			datas.put("info", "请点击发送验证码！");
			context.getDatas().put("result", datas);
			return;
		}
		String AA032_ = getParam("AA032");
		if(!AA032.equals(AA032_)) {
			datas.put("isPass", false);
			datas.put("info", "手机号与接收验证码手机号不一致！");
			context.getDatas().put("result", datas);
			return;
		}
		if (AA032!=null && context.getSessionVal("AF016")!=null) {
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF014 desc) where rownum = 1", 
					AA032, getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					datas.put("isPass", false);
					datas.put("info", "验证码超时");
					context.getDatas().put("result", datas);
					return;
				}else{
					//处理登录
					String findUser = " select * from RC10 where AA032 = ? and AA003 = '1' AND AAE016 = '1'";
					Model m_ = SqlHelper.queryOne(findUser, AA032);
					context.getServletSession().setAttribute("user", m_);//session中保存用户信息
					m_.put("isPass", true);
					context.getDatas().put("result", m_);
					context.getServletSession().removeAttribute("AF016");
					context.getServletSession().removeAttribute("AA032");
				}
			} else {
				datas.put("isPass", false);
				datas.put("info", "验证码输入错误");
				context.getDatas().put("result", datas);
				return;
			}
		}else{
			datas.put("isPass", false);
			datas.put("info", "验证码已失效，请重新获取");
			context.getDatas().put("result", datas);
			return;
		}
	
	}
	
	public static void main(String[] args) {
		String AAF013 = "123456789";
		String AAB301 = AAF013.substring(0, 6);
		System.out.println("f==="+AAF013+",B==="+AAB301);
	}
}
